package com.example.demo.controller;

import com.example.demo.utils.PassToken;
import com.example.demo.utils.ServiceResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@CrossOrigin
@RestController
public class CommonController {
    @Value("d:/upload")
    String uploadPath;
    //文件上传

    @PostMapping("/upload")
    public ServiceResponse<String> uploadFile(MultipartFile file) throws IOException{
        if (file.getSize()>0){
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formatDate = currentDate.format(formatter);
            File path = new File(uploadPath,formatDate);
            if (!path.exists()){
                path.mkdirs();
            }
            String newfileName = UUID.randomUUID()+
                    file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            File f = new File(path,newfileName);
            file.transferTo(f);
            return ServiceResponse.createBySuccess(200,"/upload/"+formatDate+"/"+newfileName,"上传成功");

        }else {
            return ServiceResponse.createBySuccess(500,"","上传失败");
        }
    }
}
